#include "mainwindow.h"
#include "mainwidget.h"
#include "settingdialog.h"

#include <QAction>
#include <QApplication>
#include <QCloseEvent>
#include <QMenu>
#include <QSystemTrayIcon>

MainWindow::MainWindow(QWidget* parent)
    : QMainWindow(parent)
    , m_trayIcon(new QSystemTrayIcon(this))
{
    setCentralWidget(new MainWidget(this));
    m_trayIcon->setIcon(QApplication::windowIcon());
    m_trayIcon->setToolTip(QApplication::applicationName());
    m_trayIcon->show();

    QMenu* menu = new QMenu(this);
    menu->addAction(QIcon(":/icon/image/show.png"), tr("Show"), this, [=]() {
        show();
    });
    menu->addAction(QIcon(":/icon/image/hide.png"), tr("Hide"), this, [=]() {
        hide();
    });
    menu->addSeparator();
    menu->addAction(QIcon(":/icon/image/shortcut.png"), tr("Setting"), this, [=]() {
        SettingDialog* settingDialog = new SettingDialog(this);
        settingDialog->exec();
        delete settingDialog;
        settingDialog = nullptr;
    });
    menu->addAction(QIcon(":/icon/image/about.png"), tr("About"), this, [=]() {
    });
    menu->addAction(QIcon(":/icon/image/quit.png"), tr("Quit"), this, [=]() {
        exit(0);
    });

    m_trayIcon->setContextMenu(menu);

    connect(m_trayIcon, &QSystemTrayIcon::activated, this, [=](QSystemTrayIcon::ActivationReason reason) {
        if (reason == QSystemTrayIcon::Trigger)
            isHidden() ? show() : hide();
    });

    setWindowFlags(windowFlags() & ~Qt::WindowMinMaxButtonsHint | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::Popup | Qt::Tool);
    resize(minimumSizeHint());
    setCursor(QCursor(Qt::DragMoveCursor));
}

MainWindow::~MainWindow()
{
}

void MainWindow::closeEvent(QCloseEvent* event)
{
    if (event)
        event->ignore();

    hide();
}

void MainWindow::mousePressEvent(QMouseEvent* event)
{
    m_lastPos = event->globalPos();
}

void MainWindow::mouseMoveEvent(QMouseEvent* event)
{
    int dx = event->globalX() - m_lastPos.x();
    int dy = event->globalY() - m_lastPos.y();
    m_lastPos = event->globalPos();
    move(x() + dx, y() + dy);
}

void MainWindow::mouseReleaseEvent(QMouseEvent* event)
{
    int dx = event->globalX() - m_lastPos.x();
    int dy = event->globalY() - m_lastPos.y();
    move(x() + dx, y() + dy);
}
